package com.jsy.common.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * 在common微服务中编写拦截器，设置请求信息
 */
public class FeignRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        //顺带把其它头部的信息也携带过去
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes!=null){
            //获取request
            HttpServletRequest request = requestAttributes.getRequest();
            //获取头部信息
            Enumeration <String>headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()){
                //头部属性名
                String name = headerNames.nextElement();
                //头部属性值
                String value = request.getHeader(name);
                //设置头部属性
                requestTemplate.header(name,value);
            }
        }
    }
}
